package com.helloscala.web
package snippet

import scala.xml.NodeSeq

import net.liftweb.http.{S, DispatchSnippet}
import net.liftweb.util.Helpers._
import net.liftweb.common.{Full, Box}
import com.helloscala.model.MTag

object TagSnippet extends DispatchSnippet {
  def dispatch = {
    case "datas" => datas
    case "tagTopics" => tagTopics
    case "detailTitle" => detailTitle
    case "popularTags" => popularTags
  }

  def datas(nodeSeq: NodeSeq): NodeSeq = {
    val curPage = H.param("cur_page", 1)
    val limit = S.attr("limit") or S.param("limit") flatMap (asInt) openOr H.defaultLimit
    val userId = H.param("user_id")

    val pagination = MTag.pagination(curPage, limit, userId)
    val cssSel =
      "#tag-total *" #> pagination.total &
        ".data-tags" #> ("a" #> pagination.page.map {
          tag =>
            "a [href]" #> W.hrefTag(tag.tag) &
              "a [title]" #> tag.size &
              ".label *" #> tag.tag &
              ".label [class+]" #> _tagLabel(tag.size)
        }) &
        "#tag-pagination *" #> pagination.pagination("")

    cssSel(nodeSeq)
  }

  def tagTopics(nodeSeq: NodeSeq): NodeSeq =
    W.reqTag.is match {
      case Full(tag) =>
        <div data-lift={s"embed?what=/p/topic/_topics;title=${tag.tag};len=20;showPagination=true;tagId=${tag.tag}"}></div>
      case _ =>
        NodeSeq.Empty
    }

  def popularTags(nodeSeq: NodeSeq): NodeSeq = {
    val limit = S.attr("limit") or S.param("limit") flatMap (asInt) openOr 50
    val tags = MTag.findAllPopular(limit)

    val cssSel =
      ".data-tags" #> ("a" #> tags.map {
        tag =>
          "a [href]" #> W.hrefTag(tag.tag) &
            ".label [class+]" #> _tagLabel(tag.size) &
            ".label *" #> tag.tag
      })

    cssSel(nodeSeq)
  }

  @inline
  private def _tagLabel(size: Long) =
    size match {
      case i if i < 10L => "label-default"
      case i if i < 100L => "label-info"
      case i if i < 500L => "label-success"
      case i if i < 1000L => "label-primary"
      case i if i < 5000L => "label-warning"
      case _ => "label-dangers"
    }

  def detailTitle(nodeSeq: NodeSeq): NodeSeq = {
    val cssSel =
      "* -*" #> S.param("tag_id").openOr("")

    cssSel(nodeSeq)
  }
}
